<template>
  <v-card 
    class="student-card" 
    :class="[statusClass, { 'card-departed': isDeparted }]"
    @click="handleCardClick"
    variant="flat"
    elevation="0"
    hover
  >
    <v-card-text class="pa-3">
      <!-- 学生基本信息 -->
      <div class="d-flex align-center mb-2">
        <v-avatar :color="getAvatarColor(student.name)" size="40" class="me-3">
          <span class="text-white font-weight-bold">{{ student.name.charAt(0) }}</span>
        </v-avatar>
        <div class="flex-grow-1">
          <h4 class="text-subtitle-1 font-weight-bold mb-0">{{ student.name }}</h4>
          <p class="text-caption text-medium-emphasis mb-0">{{ student.student_no }}</p>
        </div>
        
        <v-chip
          :color="getDepartureStatusColor(student.departure_status)"
          size="small"
          :variant="isDeparted ? 'elevated' : 'outlined'"
          class="status-chip"
        >
          {{ getDepartureStatusText(student.departure_status) }}
        </v-chip>
      </div>
      
      <!-- 状态芯片 -->
      <div class="status-chips d-flex flex-wrap gap-1 mb-2">
        <!-- 考勤状态 -->
        <v-chip
          size="small"
          :color="getAttendanceStatusColor(student.attendance_status)"
          variant="elevated"
        >
          {{ getAttendanceStatusText(student.attendance_status) }}
        </v-chip>
        
        <!-- 离校方式 -->
        <v-chip
          v-if="student.departure_method"
          size="small"
          :color="getDepartureMethodColor(student.departure_method)"
          variant="elevated"
        >
          {{ getDepartureMethodText(student.departure_method) }}
        </v-chip>
      </div>
      
      <!-- 离园时间 -->
      <div v-if="student.departure_time" class="d-flex align-center mb-2">
        <v-icon size="16" class="me-2 text-medium-emphasis">mdi-clock</v-icon>
        <span class="text-caption">离园: {{ student.departure_time }}</span>
      </div>
      
      <!-- 备注信息 -->
      <div v-if="student.notes" class="notes-section mb-2">
        <v-icon size="14" class="me-1 text-medium-emphasis">mdi-note-text</v-icon>
        <span class="text-caption">{{ student.notes }}</span>
      </div>
      

      
      <!-- 快速操作按钮 -->
      <div class="quick-actions mt-2">
        <!-- 离校方式设置按钮 -->
        <v-btn-group v-if="canSetDepartureMethod" variant="outlined" density="compact" divided class="mb-2">
          <v-btn
            size="small"
            :color="student.departure_method === 'bus' ? 'blue' : 'grey'"
            @click.stop="setDepartureMethod('bus')"
          >
            <v-icon size="16">mdi-bus-school</v-icon>
          </v-btn>
          <v-btn
            size="small"
            :color="student.departure_method === 'parent_pickup' ? 'green' : 'grey'"
            @click.stop="setDepartureMethod('parent_pickup')"
          >
            <v-icon size="16">mdi-account-heart</v-icon>
          </v-btn>
          <v-btn
            size="small"
            :color="student.departure_method === 'after_school' ? 'purple' : 'grey'"
            @click.stop="setDepartureMethod('after_school')"
          >
            <v-icon size="16">mdi-school</v-icon>
          </v-btn>
          <v-btn
            size="small"
            :color="student.departure_method === 'special_course' ? 'orange' : 'grey'"
            @click.stop="setDepartureMethod('special_course')"
          >
            <v-icon size="16">mdi-palette</v-icon>
          </v-btn>
        </v-btn-group>
        
        <!-- 确认离班按钮 -->
        <div class="d-flex gap-1 mb-2">
          <v-btn
            size="small"
            color="success"
            variant="elevated"
            @click.stop="confirmDeparture"
            flex
          >
            <v-icon size="16" class="me-1">mdi-check-circle</v-icon>
            确认离班
          </v-btn>
        </div>
        

        
        <!-- 课后离班按钮 -->
        <div v-if="canLeaveAfterSchoolClass" class="d-flex gap-1">
          <v-btn
            size="small"
            color="warning"
            variant="elevated"
            @click.stop="leaveAfterSchoolClass"
            flex
          >
            <v-icon size="16" class="me-1">mdi-exit-run</v-icon>
            课后离班
          </v-btn>
        </div>
        
        <!-- 请假按钮 -->
      </div>
      
      <!-- 操作按钮 -->
      <div class="actions mt-2">
        <div class="d-flex gap-1 mb-2">
          <v-btn
            size="small"
            color="primary"
            variant="outlined"
            @click.stop="setDeparture"
            flex
          >
            <v-icon size="16" class="me-1">mdi-exit-to-app</v-icon>
            设置离园
          </v-btn>
          <v-btn
            size="small"
            color="error"
            variant="outlined"
            @click.stop="setAbnormal"
            flex
          >
            <v-icon size="16" class="me-1">mdi-alert</v-icon>
            设置异常
          </v-btn>
        </div>
        <v-btn
          size="small"
          color="info"
          variant="outlined"
          @click.stop="editNotes"
          block
        >
          <v-icon size="16" class="me-1">mdi-note-edit</v-icon>
          编辑备注
        </v-btn>
      </div>
    </v-card-text>
  </v-card>
</template>

<script setup>
import { computed } from 'vue'
import { useStudentsStore } from '@/stores/students'
import { useAuthStore } from '@/stores/auth'

const props = defineProps({
  student: {
    type: Object,
    required: true
  },

})

const emit = defineEmits(['update-departure', 'quick-update', 'confirm-departure', 'set-departure', 'set-abnormal', 'edit-notes'])

const studentStore = useStudentsStore()
const userStore = useAuthStore()

// 计算属性
const isDeparted = computed(() => {
  return props.student.departure_status && props.student.departure_status !== 'not_left'
})

const canDepart = computed(() => {
  return props.student.arrival_status === 'present'
})

// 是否已标记离园（但未确认）
const isMarked = computed(() => {
  return props.student.departure_status && 
         props.student.departure_status !== 'not_left' && 
         !props.student.departure_confirmed
})

// 是否已确认离校
const isConfirmed = computed(() => {
  return props.student.departure_confirmed === true
})

const canSetDepartureMethod = computed(() => {
  // 只有已进校且未设置离校方式的学生可以设置离校方式
  // 14:00后只有管理员可以设置
  const currentHour = new Date().getHours()
  const isAfter14 = currentHour >= 14
  const isAdmin = userStore.user?.role === 'admin'
  
  return props.student.attendance_status === 'arrived' && 
         !props.student.departure_method &&
         (!isAfter14 || isAdmin)
})

const canConfirmDeparture = computed(() => {
  // 教师可以确认已设置离校方式但未确认离班的学生
  return props.student.attendance_status === 'arrived' && 
         props.student.departure_method &&
         !props.student.departure_timestamp &&
         ['teacher', 'admin'].includes(userStore.user?.role)
})



const canLeaveAfterSchoolClass = computed(() => {
  // 课后教师可以让已进班的学生离班（直接离校）
  return props.student.attendance_status === 'class_entered' &&
         userStore.user?.role === 'after_school_teacher'
})

const canRequestLeave = computed(() => {
  // 教师和管理员可以为学生请假
  return props.student.attendance_status === 'not_arrived' &&
         ['teacher', 'admin'].includes(userStore.user?.role)
})

const statusClass = computed(() => {
  // 根据离园状态返回对应的CSS类
  if (props.student.departure_status) {
    return `status-${props.student.departure_status}`
  }
  // 根据入园状态返回默认类
  if (props.student.arrival_status === 'present') return 'status-ready'
  return 'status-waiting'
})

// 方法
const handleCardClick = () => {
  emit('update-departure', props.student)
}

const setDeparture = () => {
  emit('set-departure', props.student)
}

const setAbnormal = () => {
  emit('set-abnormal', props.student)
}

const editNotes = () => {
  emit('edit-notes', props.student)
}

const setDepartureMethod = async (method) => {
  try {
    await studentStore.setDepartureMethod(props.student.id, method)
    emit('updated')
  } catch (error) {
    console.error('设置离校方式失败:', error)
  }
}

const confirmDeparture = () => {
  // 触发确认离班事件，由父组件处理
  emit('confirm-departure', props.student)
}



const leaveAfterSchoolClass = async () => {
  try {
    await studentStore.leaveAfterSchoolClass(props.student.id)
    emit('updated')
  } catch (error) {
    console.error('课后离班失败:', error)
  }
}

const requestLeave = async () => {
  try {
    await studentStore.requestLeave(props.student.id)
    emit('updated')
  } catch (error) {
    console.error('请假失败:', error)
  }
}

const getAvatarColor = (name) => {
  const colors = ['primary', 'secondary', 'accent', 'info', 'success', 'warning']
  const index = name.charCodeAt(0) % colors.length
  return colors[index]
}

const getAttendanceStatusColor = (status) => {
  const colors = {
    'arrived': 'success',
    'not_arrived': 'grey',
    'on_leave': 'warning',
    'left_school': 'info',
    'abnormal': 'error',
    'left_class': 'orange',
    'entered_class': 'purple'
  }
  return colors[status] || 'grey'
}

const getAttendanceStatusText = (status) => {
  const texts = {
    'arrived': '已进校',
    'not_arrived': '未到',
    'on_leave': '请假',
    'left_school': '已离校',
    'abnormal': '异常',
    'left_class': '已离班',
    'entered_class': '已进班'
  }
  return texts[status] || '未知'
}

const getDepartureMethodColor = (method) => {
  const colors = {
    'bus': 'blue',
    'parent_pickup': 'green',
    'after_school': 'purple',
    'special_course': 'orange'
  }
  return colors[method] || 'grey'
}

const getDepartureMethodText = (method) => {
  const texts = {
    'bus': '校车',
    'parent_pickup': '家长接领',
    'after_school': '托班',
    'special_course': '特色课程'
  }
  return texts[method] || '未设置'
}

const getDepartureStatusColor = (status) => {
  const colors = {
    'not_left': 'grey',
    'left_school': 'success',
    'class_left': 'orange', 
    'class_entered': 'purple'
  }
  return colors[status] || 'grey'
}

const getDepartureStatusText = (status) => {
  const texts = {
    'not_left': '未离园',
    'left_school': '已离校',
    'class_left': '已离班',
    'class_entered': '已进班'
  }
  return texts[status] || ''
}
</script>

<style scoped>
.student-card {
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  height: 100%;
  border: none !important;
  border-radius: 12px;
}

.student-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.student-card.card-departed {
  background: linear-gradient(135deg, #e8f5e8 0%, #f0f9f0 100%);
  color: #2e7d32;
}

.student-card.status-ready {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  color: #1565c0;
}

.student-card.status-waiting {
  background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%);
  color: #e65100;
}

/* 离园状态样式 - 简化版本 */
.student-card.status-departed,
.student-card.status-bus,
.student-card.status-parent,
.student-card.status-aftercare,
.student-card.status-special,
.student-card.status-parent_pickup,
.student-card.status-after_school,
.student-card.status-special_course {
  background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%);
  color: #2e7d32;
}

.student-card.status-abnormal {
  background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
  color: #c62828;
}

.student-card.status-null,
.student-card.status-undefined,
.student-card.status-not_left {
  background: linear-gradient(135deg, #f5f5f5 0%, #eeeeee 100%);
  color: #424242;
}

.notes-section {
  background-color: rgba(33, 150, 243, 0.08);
  padding: 4px 8px;
  border-radius: 4px;
  border-left: 2px solid #2196F3;
}

.status-chip {
  font-weight: 600;
}

.quick-actions .v-btn {
  min-width: 32px !important;
}



.v-card-text {
  padding: 12px !important;
}

/* 响应式调整 */
@media (max-width: 600px) {
  .quick-actions .v-btn-group {
    flex-wrap: wrap;
  }
  
  .quick-actions .v-btn {
    flex: 1;
    min-width: 40px !important;
  }
}
</style>
